﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace DiscoveryLogic.Workflows.Components.Markov.MaxEnt
{
    public class FileEventReader : ITrainingEventReader, IDisposable
    {
        private StreamReader mReader;
        private string mCurrentLine;

        private char[] mWhitespace;

        public FileEventReader(string fileName)
        {
            mReader = new StreamReader(fileName, System.Text.Encoding.UTF7);
            mWhitespace = new char[] { '\t', '\n', '\r', ' ' };
        }

        public virtual bool HasNext()
        {
            mCurrentLine = mReader.ReadLine();
            return (mCurrentLine != null);
        }

        public virtual TrainingEvent ReadNextEvent()
        {
            string[] tokens = mCurrentLine.Split(mWhitespace);
            string outcome = tokens[0];
            string[] context = new string[tokens.Length - 1];
            Array.Copy(tokens, 1, context, 0, tokens.Length - 1);

            return (new TrainingEvent(outcome, context));
        }

        public static string ToLine(TrainingEvent eventToConvert)
        {
            System.Text.StringBuilder lineBuilder = new System.Text.StringBuilder();
            lineBuilder.Append(eventToConvert.Outcome);
            string[] context = eventToConvert.GetContext();
            for (int contextIndex = 0, contextLength = context.Length; contextIndex < contextLength; contextIndex++)
            {
                lineBuilder.Append(" " + context[contextIndex]);
            }
            lineBuilder.Append(System.Environment.NewLine);
            return lineBuilder.ToString();
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                mReader.Close();
            }
        }

        ~FileEventReader()
        {
            Dispose(false);
        }
    }
}
